﻿(function () {
    var options, //传入的参数
        cacheData = [],
       curLoc, curLocAddress,
        myGeo,
        $mapTipMsg,
        map = null;

    var defaults = {
        "MapCity": '深圳',
        "MapZoom": 15,
        "ReturnUrl": "",
        "MapData": null,
        "SelectBtnText": null,
        "FromType": 0,
        "CurUserLocation": null,
        UserAddress: null,
        CurUserLocMapFromType: 1
    };

    function writeLog(obj) {
        if (window.lzlLogDebug && typeof window.lzlLogDebug.debug == 'function') {
            window.lzlLogDebug.debug.apply(this, arguments);
        }
    }

    function getShopMapMsg(shop) {
        var content = '<div class="shopInfo">';
        content += shop.InfoWindowMsg;
        content += '<div>距离：' + shop.Distance.toFixed(0) + 'm</div>';
        content += '<div class="shopBottom"><a href="javascript:;" onclick="selectShopMapApi.select(\'' + shop.Id + '\',\'' + shop.Distance.toFixed(0) + '\')">' + options.SelectBtnText + '</a></div>';
        content += '</div>';
        return content;
    }

    function mapCenterAndZoom(point, zoom) {
        //map.setCenter(point);
        //map.setZoom(zoom);
        map.centerAndZoom(point, zoom);
    }

    /*开启信息窗口*/
    function OpenInfoWindow(content, loc) {
        var point = new BMap.Point(loc.lng, loc.lat);
        var infoWindow = new BMap.InfoWindow(content);
        mapCenterAndZoom(point, 15);
        map.openInfoWindow(infoWindow, point);
    }

    function ShowMapShop(info, num) {
        OpenInfoWindow(getShopMapMsg(info), { lng: info.lng, lat: info.lat });
    }

    function SignSearchedShopOnMap() {
        map.clearOverlays();
        signCurPosition(curLocAddress);
        $.each(cacheData, function (i, item) {
            var marker1 = new BMap.Marker(new BMap.Point(item.lng, item.lat), i + 1);
            var marker = new MapExt.CustomNumberOverlay(new BMap.Point(item.lng, item.lat), i + 1);
            map.addOverlay(marker);
            //map.addOverlay(marker1);
            marker.addEventListener("click", function (e) {
                ShowMapShop(item, i + 1);
            });
        });
        setTimeout(function () {
            cacheData.length > 0 && ShowMapShop(cacheData[0], 1);
        }, 1000);
    }

    /*定位，获取当前经纬度*/
    function GetLocationLngLat() {
        if (options.CurUserLocation) {
            if (options.CurUserLocMapFromType != 5) {
                var convertor = new BMap.Convertor();
                var pointArr = [];
                pointArr.push(options.CurUserLocation);
                convertor.translate(pointArr, options.CurUserLocMapFromType, 5, function (data) {
                    curLocAddress = options.UserAddress;
                    if (data.status === 0) {
                        curLoc = data.points[0];
                        return QueryServerData();
                    } else {
                        getCurrentPosition();
                    }
                });
            } else {
                curLoc = new BMap.Point(options.CurUserLocation.lng, options.CurUserLocation.lat);
                curLocAddress = options.UserAddress;
                return QueryServerData();
            }
        } else if (options.UserAddress) {
            searchMapAddress(options.UserAddress);
        } else {
            getCurrentPosition();
        }
    }

    function searchMapAddress(addr) {
        var city = options.MapCity;
        $mapTipMsg.html('<b>正在解析用户地址。。。</b>');
        writeLog('正在解析用户地址' + addr);
        myGeo.getPoint(addr, function (point) {
            $mapTipMsg.hide();
            if (point) {
                curLoc = point;
                curLocAddress = addr;
                writeLog('解析地址:', point);
                QueryServerData();
            } else {
                alert("地址[" + addr + "]解析失败!");
            }
        }, city);
    }

    function getCurrentPosition() {
        var geolocation = new BMap.Geolocation();
        $mapTipMsg.html('<b>正在定位您当前的位置。。。</b>');
        geolocation.getCurrentPosition(function (r) {
            $mapTipMsg.hide();
            if (this.getStatus() == BMAP_STATUS_SUCCESS) {
                curLoc = r.point;
                if (r.address) {
                    curLocAddress = r.address['province'] + r.address['city'] + r.address['district'] + r.address['street'];
                }
                writeLog(r);
                QueryServerData();
            }
            else {
                alert('failed' + this.getStatus());
            }
        }, { enableHighAccuracy: true });
    }

    function signCurPosition(addr) {
        var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
            offset: new BMap.Size(10, 25),
            imageOffset: new BMap.Size(0, 0 - 10 * 25)
        });
        var marker = new BMap.Marker(curLoc, { icon: myIcon });
        map.addOverlay(marker);
        marker.setLabel(new BMap.Label('位置：' + addr, { offset: new BMap.Size(-45, -20) }));
    }

    function QueryServerData() {
        $mapTipMsg.hide();
        cacheData = options.MapData || [];
        $.each(cacheData, function (i, item) {
            item.Distance = mapLibs.getDistance(curLoc, { lng: item.lng, lat: item.lat });
        });
        cacheData.sort(itemMapSort);
        SignSearchedShopOnMap();
    }

    function itemMapSort(a, b) {
        if (a.Distance > b.Distance) {
            return 1;
        }
        if (a.Distance < b.Distance) {
            return -1;
        }
        return 0;
    }

    var api = {
        init: function (opts) {
            options = $.extend(true, {}, defaults, opts);
            writeLog('info', options);
            map = new BMap.Map("allmap");
            myGeo = new BMap.Geocoder();
            map.centerAndZoom(options.MapCity, options.MapZoom);
            var geolocationControl = new MapExt.BackCenterControl(BMAP_ANCHOR_BOTTOM_RIGHT);
            geolocationControl.addEventListener("click", function (e) {
                map.centerAndZoom(curLoc, 15);
            });
            map.enableScrollWheelZoom();
            map.addControl(geolocationControl);
            $mapTipMsg = $('#mapTipMsg').show();
            map.addEventListener('load', function () {
                //  GetLocationLngLat();
                setTimeout(GetLocationLngLat, 2000);
            });
        },
        select: function (id, distance) {
            mapCommon.callback(options, { Id: id, Distance: distance });
        }
    };
    window.selectShopMapApi = api;
})();